package com.wowangz.cms.dailyoperation.chargemanagenew.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.dailyoperation.chargemanagenew.pojo.Charge;
import com.wowangz.cms.dailyoperation.chargemanagenew.service.ChargeService;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;

@Scope("prototype")
@Controller
public class ChargeController extends BaseController{

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(ChargeController.class);
	
	/**
	 * 点击菜单"收费管理"显示“收费管理”列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/chargemanage/tochargeInfoList.web")
	public String tochargeInfoList(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "/WEB-INF/jsp/dailyoperation/chargemanagenew/chargeInfoList";
	}
	
	/**
	 * 打开“服务管理”列表加载列表数据
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/dailyoperation/chargemanage/querychargeListInfoDataGrid.json")
	public void querychargeListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		ChargeService chargeService = (ChargeService) IssTransactionContainer.getInstance(ChargeService.class, false);
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);

			
			long resultCount = chargeService.findResultCount(map);
			List<Charge> resultList = chargeService.findResultList(map);

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);
			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("serviceid", DataTypeConstant.LONG);
			dataStyle.addDepict("servicenum", DataTypeConstant.STRING);
			dataStyle.addDepict("servicename", DataTypeConstant.STRING);
			dataStyle.addDepictByFunction("isproposed", SysConstant.ProposedOrMonth.class, "getName", new Class[]{long.class});
			dataStyle.addDepict("proposedprice", DataTypeConstant.AMOUNT_2);
			dataStyle.addDepictByFunction("ismonth", SysConstant.ProposedOrMonth.class, "getName", new Class[]{long.class});
			dataStyle.addDepict("monthprice", DataTypeConstant.AMOUNT_2);
			dataStyle.addDepictByFunction("checkstatus", SysConstant.CheckStatus.class, "getName", new Class[]{long.class});
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转修改服务页面（新增或者修改）
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/chargemanage/toChargeAddOrUpdate.web")
	public String toChargeAddOrUpdate(HttpServletRequest request, HttpServletResponse response, Model model) {
		ChargeService chargeService = (ChargeService)IssTransactionContainer.getInstance(ChargeService.class, false);
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		Charge charge = null;
		String serviceid = request.getParameter("serviceid");
		try {
			hashMap.put("serviceid", serviceid);
			hashMap.put("statusid", SysConstant.RecordStatus.VALID);
			charge = chargeService.queryChargeByID(hashMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(charge.getId() == null){
			//如果收费管理表中的serviceid为null表示此服务没有任何收费数据,进行新增页面中
			model.addAttribute("charge",charge);
			model.addAttribute("serviceid",serviceid);
			return "/WEB-INF/jsp/dailyoperation/chargemanagenew/chargeInfoAdd";
		}else{
			//否则进入修改页面
			Long yes = SysConstant.ProposedOrMonth.Yes;
			model.addAttribute("charge",charge);
			model.addAttribute("yes",yes);
			return "/WEB-INF/jsp/dailyoperation/chargemanagenew/chargeInfoUpdate";
		}
	}
	
	/**
	 * 修改服务
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/chargemanage/updateCharge.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateCharge(HttpServletRequest request, HttpServletResponse response, Model model) {
		ChargeService chargeService = (ChargeService)IssTransactionContainer.getInstance(ChargeService.class, false);
		Charge charge = (Charge)ServletUtils.getParametersToBaseEntity(request, Charge.class);
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		try{
			
			hashMap.put("id", charge.getId());
			hashMap.put("checkstatus", SysConstant.CheckStatus.SAVE);
			hashMap.put("modifyuserid",getUserContext().getLoginUser().getId());
			hashMap.put("modifytime",new Date());
			hashMap.put("statusid", SysConstant.RecordStatus.VALID);
			if(charge.getDatastatus() == SysConstant.DataStatus.CHECKED){
				//如果修改的数据是之前复核过的
				//修改收费单中的状态
				
				chargeService.updatechargemanageByMap(hashMap);
				
				//修改收费临时表
				hashMap.put("isproposed", charge.getIsproposed());
				hashMap.put("proposedprice", charge.getProposedprice());
				hashMap.put("ismonth", charge.getIsmonth());
				hashMap.put("monthprice", charge.getMonthprice());
				chargeService.updatechargemanageTempByMap(hashMap);
			}else{
				//如果不是复核过，而是新增的并未有复核
				hashMap.put("isproposed", charge.getIsproposed());
				hashMap.put("proposedprice", charge.getProposedprice());
				hashMap.put("ismonth", charge.getIsmonth());
				hashMap.put("monthprice", charge.getMonthprice());
				chargeService.updatechargemanageByMap(hashMap);
				chargeService.updatechargemanageTempByMap(hashMap);
			}
			
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert6"));
			userContext.setCloseWindow(true);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/chargemanagenew/chargeInfoList";
	}
	
	/**
	 * 新增服务
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/chargemanage/addCharge.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addCharge(HttpServletRequest request, HttpServletResponse response, Model model) {
		ChargeService chargeService = (ChargeService)IssTransactionContainer.getInstance(ChargeService.class, true);
		Charge charge = (Charge)ServletUtils.getParametersToBaseEntity(request, Charge.class);
		
		try{
			charge.setCheckstatus(SysConstant.CheckStatus.SAVE);
			charge.setStatusid(SysConstant.RecordStatus.VALID);
			charge.setDatastatus(SysConstant.DataStatus.INSERT);
			charge.setInputuserid(getUserContext().getLoginUser().getId());
			charge.setInputtime(new Date());
			charge.setModifyuserid(getUserContext().getLoginUser().getId());
			charge.setModifytime(new Date());
			chargeService.insertchargemanage(charge);
			//往临时表里插入一条数据，用来复核
			chargeService.insertchargemanageTemp(charge);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/chargemanagenew/chargeInfoList";
	}
	
	/**
	 * 删除收费
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/dailyoperation/chargemanage/deleteCharge.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteCharge(HttpServletRequest request, HttpServletResponse response, Model model){
		ChargeService chargeService = (ChargeService)IssTransactionContainer.getInstance(ChargeService.class, false);
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try{
			Long id = Long.parseLong(request.getParameter("id"));
			HashMap<String,Object> hashMap = new HashMap<String, Object>();
			hashMap.put("id", id);
			chargeService.deleteCharge(hashMap);
			chargeService.deleteChargeTemp(hashMap);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	/**
	 * 跳转明细页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/chargemanage/intochargeView.web")
	public String intochargeView(HttpServletRequest request, HttpServletResponse response, Model model) {
		ChargeService chargeService = (ChargeService)IssTransactionContainer.getInstance(ChargeService.class, false);
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		Charge charge = null;
		Charge chargeCheck = null;
		String serviceid = request.getParameter("serviceid");
		try {
			hashMap.put("serviceid", serviceid);
			hashMap.put("statusid", SysConstant.RecordStatus.VALID);
			charge = chargeService.queryChargeByID(hashMap);
			chargeCheck = chargeService.queryChargeCheckByID(hashMap);
			Long yes = SysConstant.ProposedOrMonth.Yes;
			model.addAttribute("yes",yes);
			model.addAttribute("charge",charge);
			model.addAttribute("chargeCheck",chargeCheck);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/chargemanagenew/chargeView";
	}
}
